import { reqCartList, reqDeleteCartById, reqUpdateCheckedById } from "@/api"

const state = {
  cartList: []
}
const mutations = {
  GETCARTLIST (state, cartList) {
    state.cartList = cartList
  }
}
const actions = {
  // 获取购物车列表数据
  async getCartList (context) {
    const {data: res} = await reqCartList ()
    if (res.code == 200) {
      context.commit ('GETCARTLIST', res.data)
    }
  },
  // 删除购物车商品
  async deleteCartListById (context, skuId) {
    const {data: res} = await reqDeleteCartById (skuId)
    if (res.code == 200) {
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  // 修改购物车商品选中状态
  async updateCheckedById (context, {skuId, isChecked}) {
    const {data: res} = await reqUpdateCheckedById (skuId, isChecked)
    if (res.code == 200) {
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  // 删除全部选中商品
  deleteAllCheckedCart (context) {
    // context： 小仓库 commit dispatch getters state
    // 调用多次删除某一个产品
    let PromiseAll = []
    context.getters.cartList.cartInfoList.forEach(item => {
      let promise = item.isChecked == 1? context.dispatch ('deleteCartListById', item.skuId): ''
      PromiseAll.push (promise)
    });
    // 全部p1 p2成功 promise.all成功
    return Promise.all(PromiseAll)
  },
  // 全选状态修改
  updateAllCartIsChecked ({dispatch, state}, isChecked) {
    let promiseAll = []
    state.cartList[0].cartInfoList.forEach ((item) => {
      let promise = dispatch ('updateCheckedById', {skuId: item.skuId, isChecked})
      promiseAll.push (promise)
    })
    return Promise.all (promiseAll)
   
  }
}

 
const getters = {
  cartList (state) {
    return state.cartList[0] || {}
  },
}

export default {
  state,
  mutations,
  actions,
  getters
}